<template>
  <div class="config-detail">
    <p class="title">{{ data.name }}</p>
    <div v-for="v in ['standard', 'additional', 'rangeLabel']" :key="v">
      <p v-if="v === 'standard'" class="item-title">质检项</p>
      <p v-if="v === 'additional'" class="item-title">附加质检项</p>
      <p v-if="v === 'rangeLabel'" class="item-title">分数段标签</p>
      <configTable
        ref="table"
        :data="
          v === 'standard'
            ? standardItem
            : v === 'rangeLabel'
            ? rangeLabelItem
            : additionalItem
        "
        :showPagination="false"
        :rowKeyIdShow="true"
        :light="false"
        :headersConfig="false"
        :class="v"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="['move'].includes(item.prop)"
              :key="index"
              :resizable="false"
              width="40px"
            >
              <template>
                <i class="V7_iconfont V7_iconV7tubiao_yidong move"></i>
              </template>
            </u-table-column>
            <u-table-column
              v-if="
                ['num'].includes(item.prop) &&
                ['standard', 'additional'].includes(v)
              "
              :key="index"
              :label="item.label"
              :resizable="false"
              type="index"
            >
            </u-table-column>
            <u-table-column
              v-if="['scoreRange'].includes(item.prop) && v === 'rangeLabel'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              min-width="220px"
            >
              <template slot="header">
                <span>{{ item.label }}</span>
                <el-tooltip
                  content="分数必须为整数，分数段包含两端分数，不允许交叉"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 12px;
                      color: #b3b9c7;
                      margin-left: 6px;
                      cursor: pointer;
                    "
                    class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
                  ></i>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-input-number
                  :controls="false"
                  v-model="scope.row.low"
                  placeholder="请填写整数"
                  class="range-num"
                  :precision="0"
                  :min="0"
                  :max="scope.row.high - 1"
                  :disabled="!scope.row.saveBtnShow"
                  @change="handleScoreChange($event, scope, 'low')"
                />
                -
                <el-input-number
                  :controls="false"
                  v-model="scope.row.high"
                  :min="scope.row.low + 1 || 1"
                  placeholder="请填写整数"
                  :precision="0"
                  class="range-num"
                  :disabled="!scope.row.saveBtnShow"
                  @change="handleScoreChange($event, scope, 'high')"
                />
              </template>
            </u-table-column>
            <u-table-column
              v-if="['label'].includes(item.prop) && v === 'rangeLabel'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              min-width="220px"
            >
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.name"
                  placeholder="请填写"
                  clearable
                  :disabled="!row.saveBtnShow"
                ></el-input>
              </template>
            </u-table-column>
            <u-table-column
              v-if="
                ['item'].includes(item.prop) &&
                ['standard', 'additional'].includes(v)
              "
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              min-width="220px"
            >
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.name"
                  placeholder="请填写"
                  clearable
                  :disabled="!row.saveBtnShow"
                ></el-input>
              </template>
            </u-table-column>
            <u-table-column
              v-if="
                ['standardScore'].includes(item.prop) &&
                ['standard', 'additional'].includes(v)
              "
              :key="index"
              :label="item.label"
              :prop="v === 'standard' ? item.prop : '附加分项'"
              :resizable="false"
              width="150px"
            >
              <template slot-scope="{ row }">
                <span
                  v-if="v === 'additional' && row.oprateScoreItem === 'add'"
                  class="add-reduce"
                  >+</span
                >
                <span
                  v-if="v === 'additional' && row.oprateScoreItem === 'reduce'"
                  class="add-reduce"
                  >-
                </span>
                <el-input-number
                  :controls="false"
                  v-model="row.score"
                  :precision="2"
                  placeholder="请填写"
                  class="add-reduce-score"
                  :disabled="!row.saveBtnShow"
                />
              </template>
            </u-table-column>
            <u-table-column
              v-if="
                ['weight'].includes(item.prop) &&
                ['standard', 'additional'].includes(v)
              "
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              width="150px"
            >
              <template slot-scope="{ row }">
                <el-input-number
                  :controls="false"
                  v-model="row.weight"
                  :precision="0"
                  :max="100"
                  placeholder="请填写整数"
                  :disabled="!row.saveBtnShow"
                  @change="weightChange($event, row, v)"
                />
                <span class="percent">%</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="['deadly'].includes(item.prop) && v === 'standard'"
              :key="index"
              :prop="item.prop"
              :resizable="false"
            >
              <template slot="header">
                <span>{{ item.label }}</span>
                <el-tooltip
                  content="若勾选此分项为致命项，当此分项标准分值低于60分时，质检总分为0分"
                  placement="top"
                >
                  <i
                    style="
                      font-size: 12px;
                      color: #b3b9c7;
                      margin-left: 6px;
                      cursor: pointer;
                    "
                    class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
                  ></i>
                </el-tooltip>
              </template>
              <template slot-scope="{ row }">
                <el-checkbox
                  v-model="row.special"
                  :disabled="!row.saveBtnShow"
                />
              </template>
            </u-table-column>
            <u-table-column
              v-if="['oprate'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              width="100px"
              :resizable="false"
            >
              <template slot-scope="scope">
                <template v-if="scope.row.saveBtnShow">
                  <span
                    class="save-btn"
                    @click="saveItem(scope.row, v)"
                    v-functions="['qc_webchat_session_config_modify']"
                    >保存</span
                  >
                  <span
                    class="cancel-btn"
                    @click="cancelItem(scope.row)"
                    v-functions="['qc_webchat_session_config_modify']"
                    >取消</span
                  >
                </template>
                <template v-else>
                  <span
                    class="save-btn"
                    @click="editItem(scope.row)"
                    v-functions="['qc_webchat_session_config_modify']"
                    >编辑</span
                  >
                  <span
                    class="save-btn"
                    @click="delItem(scope.$index, v)"
                    v-functions="['qc_webchat_session_config_delete']"
                    >删除</span
                  >
                </template>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <div v-if="v === 'standard'" class="add-item">
        <span class="btn" @click="addItem('standard')">
          <i class="el-icon-plus"></i>
          添加质检分项
        </span>
        <span class="stand-num">当前标准总分: {{ standardTotalScore }}</span>
      </div>
      <div v-else-if="v === 'additional'" class="add-item">
        <span class="btn">
          <span @click="addItem('additional-add')"
            ><i class="el-icon-plus"></i> 添加加分项</span
          >
          <span @click="addItem('additional-reduce')"
            ><i class="el-icon-plus" style="margin-left: 20px"></i
            >添加减分项</span
          >
        </span>
        <span class="stand-num">当前附加总分: {{ additionTotalScore }}</span>
      </div>
      <div v-else class="add-item">
        <span class="btn" @click="addItem('rangeLabel')">
          <i class="el-icon-plus"></i>
          添加分数段标签
        </span>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import Sortable from 'sortablejs'
import { v4 as uuidv4 } from 'uuid'
import { commonAction } from '@/utils/common'
@Component({
  name: 'qualityLog',
  components: {
    configTable
  }
})
export default class QualityLog extends Vue {
  [x: string]: any
  @Prop() private data

  private standardItem: any = [] // 质检项

  private additionalItem: any = [] // 附加质检项

  private rangeLabelItem: any = [] // 分数段标签

  private checkHeaders: any = [
    {
      label: '',
      prop: 'move'
    },
    {
      label: '序号',
      prop: 'num'
    },
    {
      label: '质检分项',
      prop: 'item'
    },
    {
      label: '标准分值',
      prop: 'standardScore'
    },
    {
      label: '权重',
      prop: 'weight'
    },
    {
      label: '致命项',
      prop: 'deadly'
    },
    {
      label: '分数段',
      prop: 'scoreRange'
    },
    {
      label: '标签内容',
      prop: 'label'
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  @Watch('data', { immediate: true, deep: true })
  private changeData (val) { // 监听选中模板的变化
    // 过滤掉空值并赋值
    this.standardItem = (val.qualityItem && val.qualityItem.filter(v => v.name && v.score)) || []
    this.additionalItem = (val.qualityAppendItem && val.qualityAppendItem.filter(v => v.name && v.score)) || []
    this.rangeLabelItem = (val.scoreRange && val.scoreRange.filter(v => v.name && (v.low || v.low === 0) && v.high)) || []
  }

  get standardTotalScore () { // 标准总分
    let totalScore = 0
    this.standardItem.forEach(item => {
      if (item.weight || item.weight === 0) {
        totalScore += item.score * (item.weight / 100)
      } else {
        totalScore += item.score
      }
    })
    if (totalScore) {
      return totalScore.toFixed(2)
    }
    return '0.00'
  }

  get additionTotalScore () { // 附加总分
    let totalScore = 0
    this.additionalItem.forEach(item => {
      if (item.weight || item.weight === 0) {
        if (item.oprateScoreItem === 'add') {
          totalScore += item.score * (item.weight / 100)
        } else {
          totalScore -= item.score * (item.weight / 100)
        }
      } else {
        if (item.oprateScoreItem === 'add') {
          totalScore += item.score
        } else {
          totalScore -= item.score
        }
      }
    })
    if (totalScore) {
      return totalScore.toFixed(2)
    }
    return '0.00'
  }

  private handleScoreChange (curVal: any, scope: any, field: any) {
    const rangeArr: any = []
    this.rangeLabelItem.forEach((item, idx) => {
      if (item.low && item.high) {
        rangeArr.push({ range: [item.low, item.high], idx })
      }
    })
    if (rangeArr && rangeArr.length) {
      rangeArr.forEach(v => {
        // 输入的值介于其他区间内 || 区间包含其他区间
        if (((v.range[0] <= curVal && curVal <= v.range[1]) || (curVal < v.range[0] && this.rangeLabelItem[scope.$index].high > v.range[1]) || (curVal > v.range[1] && this.rangeLabelItem[scope.$index].low < v.range[0])) && scope.$index !== v.idx) {
          this.$nextTick(() => {
            this.$set(scope.row, field, undefined) // 清空数据
          })
          this.$message.error('分数段不可交叉')
        }
      })
    }
  }

  private weightChange (curVal, row, v) { // 权重和不能大于100
    let weightTotal = 0
    this[v === 'standard' ? 'standardItem' : 'additionalItem'].forEach(item => {
      if (item.weight || item.weight === 0) {
        weightTotal += item.weight
      }
    })
    if (weightTotal > 100) {
      this.$nextTick(() => { // dom更新完再更改
        row.weight = curVal - (weightTotal - 100)
      })
      this.$message.error('权重总值不能大于100')
    }
  }

  private async saveItem (row: any, v: string) { // 保存
    if ((!row.name || !row.score) && ['standard', 'additional'].includes(v)) {
      return this.$message.error('请填写质检分项或标准分值')
    }
    if ((!row.name || (!row.low && row.low !== 0) || (!row.high && row.high !== 0)) && ['rangeLabel'].includes(v)) {
      return this.$message.error('请将信息填写完整后保存')
    }
    this.updateConfigData(row, true)
  }

  private updateConfigData (row?: any, update?: boolean) {
    if (row) {
      row.saveBtnShow = false
    }
    const params = {
      url: '/im-center/action/qualityConfig/update',
      method: 'POST',
      data: {
        qualityItem: this.standardItem,
        qualityAppendItem: this.additionalItem,
        scoreRange: this.rangeLabelItem,
        _id: this.data._id
      }
    }
    commonAction(params).then(res => {
      if (res.success) {
        this.$message.success('操作成功')
        if (update) {
          this.$emit('updateConfigModels')
        }
      }
    })
  }

  private delItem (index: any, type: any) {
    this.$confirm('确定删除此分项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      switch (type) {
        case 'standard':
          this.standardItem.splice(index, 1)
          this.updateConfigData()
          break
        case 'additional':
          this.additionalItem.splice(index, 1)
          this.updateConfigData()
          break
        case 'rangeLabel':
          this.rangeLabelItem.splice(index, 1)
          this.updateConfigData()
          break
      }
      this.$emit('updateConfigModels')
    })
  }

  private cancelItem (row: any) {
    row.saveBtnShow = false
  }

  private editItem (row: any) {
    row.saveBtnShow = true
  }

  private addItem (type: string) {
    switch (type) {
      case 'standard':
        this.standardItem.push({
          id: uuidv4().replace(/-/g, ''),
          name: '',
          score: undefined,
          weight: undefined,
          special: false,
          saveBtnShow: true
        })
        break
      case 'additional-add':
        this.additionalItem.push({
          id: uuidv4().replace(/-/g, ''),
          name: '',
          score: undefined,
          weight: undefined,
          saveBtnShow: true,
          oprateScoreItem: 'add'
        })
        break
      case 'additional-reduce':
        this.additionalItem.push({
          id: uuidv4().replace(/-/g, ''),
          item: '',
          standardScore: undefined,
          weight: undefined,
          saveBtnShow: true,
          oprateScoreItem: 'reduce'
        })
        break
      case 'rangeLabel':
        this.rangeLabelItem.push({
          id: uuidv4().replace(/-/g, ''),
          scoreRange: '',
          name: '',
          saveBtnShow: true
        })
    }
  }

  // 行拖拽
  private rowStandardDrop () {
    const standardBody = document.querySelector('.standard .el-table__body-wrapper tbody')
    const that = this
    let sortedArr = []
    const sortInstance = Sortable.create(standardBody, {
      animation: 1000,
      handle: '.move',
      onStart () {
        sortedArr = sortInstance.toArray()
      },
      onEnd ({ newIndex, oldIndex }) {
        if (that.standardItem.some(item => item.saveBtnShow)) {
          sortInstance.sort(sortedArr.sort())
          return that.$message.error('存在编辑中数据，请保存或取消')
        }
        const currRow = that.standardItem.splice(oldIndex, 1)[0]
        that.standardItem.splice(newIndex, 0, currRow)
        that.updateConfigData('', true) // 拖拽后更新数据
      }
    })
  }

  private rowAdditionalDrop () {
    const additionalBody = document.querySelector('.additional .el-table__body-wrapper tbody')
    const that = this
    let sortedArr = []
    const sortInstance = Sortable.create(additionalBody, {
      animation: 1000,
      handle: '.move',
      onStart () {
        sortedArr = sortInstance.toArray()
      },
      onEnd ({ newIndex, oldIndex }) {
        if (that.additionalItem.some(item => item.saveBtnShow)) {
          sortInstance.sort(sortedArr.sort())
          return that.$message.error('存在编辑中数据，请保存或取消')
        }
        const currRow = that.additionalItem.splice(oldIndex, 1)[0]
        that.additionalItem.splice(newIndex, 0, currRow)
        that.updateConfigData('', true) // 拖拽后更新数据
      }
    })
  }

  private rowRangeLabelDrop () {
    const rangeLabelBody = document.querySelector('.rangeLabel .el-table__body-wrapper tbody')
    const that = this
    let sortedArr = []
    const sortInstance = Sortable.create(rangeLabelBody, {
      animation: 1000,
      handle: '.move',
      onStart () {
        sortedArr = sortInstance.toArray()
      },
      onEnd ({ newIndex, oldIndex }) {
        if (that.rangeLabelItem.some(item => item.saveBtnShow)) {
          sortInstance.sort(sortedArr.sort())
          return that.$message.error('存在编辑中数据，请保存或取消')
        }
        const currRow = that.rangeLabelItem.splice(oldIndex, 1)[0]
        that.rangeLabelItem.splice(newIndex, 0, currRow)
        that.updateConfigData('', true) // 拖拽后更新数据
      }
    })
  }

  private mounted () {
    this.rowStandardDrop()
    this.rowAdditionalDrop()
    this.rowRangeLabelDrop()
  }
}
</script>
<style lang="stylus" scoped>
.config-detail
  width 100%
  overflow-y auto
  padding 24px
  .title, .item-title
    font-weight 600
    color #303753
  .item-title
    margin-top 30px
  .add-item
    margin-top 15px
    display flex
    justify-content space-between
    .btn
      color #008BEE
      cursor pointer
      i
        margin-right 3px
    .stand-num
      color #686E84
.save-btn
  color #008BEE
  margin 0 4px
  cursor pointer
.cancel-btn
  color #FC6B5C
  margin 0 4px
  cursor pointer
.resize-table
  height auto
>>> .el-input-number
  width 90%
  .el-input__inner
    text-align left
.percent
  position relative
  left -16px
.add-reduce
  position relative
  left 16px
  z-index 1
  font-weight 600
  color #303753
.add-reduce-score
  >>> .el-input__inner
    padding-left 20px
>>> .el-input__inner
  background #F3F6F9
.range-num
  >>> &.el-input-number
    width 100px
.move
  cursor move
  font-size 12px
  color #B3B9C7
>>> .el-table tbody tr:hover>td
  background-color transparent !important
>>> .el-table__body tr.hover-row>td
  background-color transparent
</style>
